<template>
    <div class="search">
        <el-select v-model="searchText" filterable clearable reserve-keyword remote loading-text="正在加载..."
            no-match-text="查询不到数据" no-data-text="没有数据" placeholder="输入要查找的姓名" default-first-option
            :remote-method="handleSearch" @focus="handleSearchInputFocus" @change="searchChange" :loading="searchLoading">
            <el-option v-for="item in searchOptions" :key="item" :value="item" />
        </el-select>



        <el-button type="primary" @click="addStu">添加</el-button>

    </div>

    <div class="export-excel">
        <el-button @click="handleExport">
            <template #icon>
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-excel"></use>
                </svg>
            </template>
            <template #default>
                导出excel
            </template>
        </el-button>
    </div>

    <div class="dataTable">
        <el-table :data="stuList" border style="width: 100%" element-loading-background="rgba(122, 122, 122, 0.3)"
            element-loading-text="正在加载" v-loading="stuTableLoading">
            <el-table-column align="center" label="头像" width="100">
                <template #default="{ row, $index }">
                    <el-image style="width: 70px; height: 70px" :src="previewImgList[$index]" :zoom-rate="1.2"
                        :preview-src-list="previewImgList" :initial-index="$index" fit="cover" />
                </template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="姓名" width="120" />
            <el-table-column align="center" prop="class" label="班级" />
            <el-table-column align="center" prop="degree" label="学历" />
            <el-table-column align="center" prop="productUrl" label="项目" />
            <el-table-column align="center" prop="cTime" label="创建时间" />
            <el-table-column align="center" label="操作">
                <template #default="{ row }">
                    <el-button v-has:read="permissionsButton">查看</el-button>
                    <el-button v-has:edit="permissionsButton" type="primary" @click="editStu(row)">编辑</el-button>
                    <el-button v-has:delete="permissionsButton" type="danger" @click="delStu(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <div class="pagenation">
        <el-pagination background layout="prev, pager, next" @current-change="handlePageSizeChange"
            :current-page="fetchTableListParam.page" hide-on-single-page :page-size="fetchTableListParam.count"
            :total="total" />
    </div>

    <s-dialog @ok="handleDialogOk" @cancel="handleDialogCancel" :reviewData="reviewData" :action="dialogAction"
        :title="dialogTitle" v-model="dialogVisible"></s-dialog>
</template>
<script setup>


import { ref, onMounted, watch, reactive } from "vue"



import * as api from "@/api/stu"

import qee from "qf-export-excel"



import sDialog from "@/components/sDialog/index.vue"



import useUser from "@/store/users"
import { ElMessage, ElMessageBox } from "element-plus"


let userStore = useUser()


let isSearch = false;



let searchList = async (key = "", isSelect = false, param = { page: 1, count: 5 }) => {

    isSearch = true;
    isSelect && (stuTableLoading.value = true)

    searchLoading.value = true;
    try {

        let res = await api.searchStuApi({ key, page: param.page, count: param.count })



        isSelect && (total.value = res.data.total)

        searchOptions.value = Array.from(new Set(res.data.data.map(item => item.name)))

        searchLoading.value = false;

        isSelect && (stuList.value = res.data.data) && (stuTableLoading.value = false)
    } catch (e) {
        console.log(e)

        searchLoading.value = false
    }
}




let searchText = ref('')



let handleSearch = (input) => {
    input && searchList(input)
}



let handleSearchInputFocus = () => {
    searchOptions.value = []
}



const searchChange = (key) => {
    if (!key) {

        fetchTableListParam.page = 1;

        isSearch = false;

        getStuList(fetchTableListParam)
    } else {

        fetchTableListParam.page = 1;

        searchList(key, true, { page: fetchTableListParam.page, count: fetchTableListParam.count })
    }
}



const searchLoading = ref(false);

const searchOptions = ref([])


let fetchTableListParam = reactive({
    page: 1,
    count: 5,
    class: ""
})


let stuTableLoading = ref(false)



const getStuList = async (param = fetchTableListParam) => {
    stuTableLoading.value = true;
    try {

        let res = await api.getStuListApi(param)

        stuList.value = res.data.data

        total.value = res.data.total
        stuTableLoading.value = false
    } catch (e) {
        console.log(e)
        stuTableLoading = false
    }
}

const stuList = ref([])



let previewImgList = ref([])



watch(stuList, (newVal) => {

    previewImgList.value = newVal.map(item => item.headimgurl ? item.headimgurl : 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png')

})



let total = ref(10)


let handlePageSizeChange = (page) => {
    fetchTableListParam.page = page;
    if (isSearch) {
        searchList(searchText.value, true, { page: fetchTableListParam.page, count: fetchTableListParam.count })
    } else {
        getStuList(fetchTableListParam)
    }
}


let titleList = [
    {
        title: "头像",
        key: "headimgurl"
    },
    {
        title: "姓名",
        key: "name"
    },
    {
        title: "班级",
        key: "class"
    },
    {
        title: "学历",
        key: "degree"
    },
    {
        title: "项目",
        key: 'productUrl'
    },
    {
        title: "创建事件",
        key: "cTime"
    }
]

const handleExport = () => {
    qee(titleList, stuList.value, '测试项目导出')
}



onMounted(() => {

    getStuList(fetchTableListParam)
})



let permissionsButton = userStore.permission.value.buttons;

let vHas = {
    mounted(el, binding) {

        if (binding.value && Array.isArray(binding.value)) {

            let has = binding.value.includes(binding.arg)
            if (!has) {

                el.style.display = 'none'
            }
        }

    }
}


let dialogVisible = ref(false)


let dialogTitle = ref('添加学员信息')

let dialogAction = ref('add')



let handleDialogOk = async (input) => {

    try {
        if (dialogAction.value === "add") {

            await api.addStuApi(input);
            ElMessage.success('添加成功')
        } else if (dialogAction.value === "edit") {

            let updateRes = await api.editStuApi(input);

            ElMessage.success('编辑成功')

        }

        getStuList()

    } catch (e) {
        console.log(e)
    }
}


let handleDialogCancel = () => {
    ElMessage.warning('取消操作')
}


let addStu = () => {

    dialogVisible.value = true

    dialogAction.value = 'add'

    dialogTitle.value = '添加学员信息'
}

let reviewData = ref();

let editStu = (row) => {
    //   console.log(123);
    dialogVisible.value = true;
    dialogTitle.value = '编辑学员信息'

    dialogAction.value = 'edit'

    reviewData.value = { ...row }
}

let delStu = async (row) => {
    ElMessageBox.confirm(
        `是否要删除 ${row.name} 这个学员的信息?该操作会永久删除这条数据,请谨慎操作!`,
        '⚠️警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {

            await api.delStuApi(row.sId);

            getStuList()

            ElMessage({
                type: 'success',
                message: `学员:${row.name},已经被删除了`,
            })
        })
        .catch(() => {
            ElMessage({
                type: 'error',
                message: '已取消删除',
            })
        })
}





</script>

<style scoped lang="scss">
.search .el-select :deep(.el-input__wrapper) {
    width: 300px;
}

.search,
.stuTable,
.export-excel,
.pagenation,
.add {
    margin: 20px 0;
}

.search {
    :deep(.el-input__wrapper) {
        min-width: 400px;
        height: 40px;
    }
}

.el-pagination {
    justify-content: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.el-input__wrapper {
    width: 300px;
}
</style>
